

package com.zdkj.subway.st.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.st.entity.SwTkWhiteCard;
import com.zdkj.subway.st.service.SwTkWhiteCardService;
import com.zdkj.subway.st.util.LocalDateConverter;
import com.zdkj.subway.st.util.LocalDateTimeConverter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;


/**
 * 白卡清单下发管理
 *
 * @author cuilei
 * @date 2020-05-26 15:05:54
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/swtkwhitecard")
@Api(value = "swtkwhitecard", tags = "白卡清单下发管理")
public class SwTkWhiteCardController {
    private static final Logger LOGGER = LoggerFactory.getLogger(SwTkWhiteCardController.class);
    @Autowired
    private final SwTkWhiteCardService swTkWhiteCardService;



    /**
     * 分页查询
     *
     * @param page            分页对象
     * @param swTkWhiteCard 白卡清单下发管理
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwTkWhiteCardPage(Page page, SwTkWhiteCard swTkWhiteCard) {
        return R.ok(swTkWhiteCardService.page(page, Wrappers.query(swTkWhiteCard)));
    }

    /**
     * 通过id查询白卡清单
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swTkWhiteCardService.getById(id));
    }

    /**
     * 新增白卡清单
     *
     * @param swTkWhiteCard 白卡清单
     * @return R
     */
    @ApiOperation(value = "新增白卡清单下发管理", notes = "新增白卡清单下发管理")
    @SysLog("新增白卡清单下发管理")
    @PostMapping
    //@PreAuthorize("@pms.hasPermission('epm_sw_ex_device_fault_add')")
    public R save(@RequestBody SwTkWhiteCard swTkWhiteCard) {
        SwTkWhiteCard defaultObj = ObjectUtils.getDefaultObj(SwTkWhiteCard.class);
        BeanUtils.copyProperties(swTkWhiteCard, defaultObj,
                ObjectUtils.getNullAndEmptyPropertyNames(swTkWhiteCard));
        return R.ok(swTkWhiteCardService.save(defaultObj));
    }

    /**
     * 修改白卡清单
     *
     * @param swTkWhiteCard 白卡清单
     * @return R
     */
    @ApiOperation(value = "修改白卡清单", notes = "修改白卡清单")
    @SysLog("修改白卡清单")
    @PutMapping
    //@PreAuthorize("@pms.hasPermission('epm_sw_ex_device_fault_edit')")
    public R updateById(@RequestBody SwTkWhiteCard swTkWhiteCard) {
        return R.ok(swTkWhiteCardService.updateById(swTkWhiteCard));
    }

    /**
     * 通过id删除白卡清单
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除白卡清单", notes = "通过id删除白卡清单")
    @SysLog("通过id删除白卡清单")
    @DeleteMapping("/{id}")
    //@PreAuthorize("@pms.hasPermission('epm_sw_ex_device_fault_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swTkWhiteCardService.removeById(id));
    }

    /**
     * 导出白卡清单
     *
     * @param response
     * @return
     */
    @ApiOperation(value = "导出白卡清单下发管理", notes = "导出白卡清单下发管理")
    @SysLog("导出白卡清单下发管理")
    @GetMapping("/export")
    public void exportExcel(@RequestParam List<Integer> ids, HttpServletResponse response) {
        List<SwTkWhiteCard> records = swTkWhiteCardService.listSelect(ids);
        InputStream excelTemplateIs = null;
        try {
            response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode("白卡清单下发管理", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");

            // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
            // {} 代表普通变量 {.} 代表是list的变量

            excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/template/export/SwTkWhiteCardServiceExcelTemplate.xlsx");
            WriteSheet writeSheet = EasyExcel.writerSheet("白卡清单下发管理").build();
            // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
            // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
            // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
            // 如果数据量大 list不是最后一行 参照另一个
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplateIs).build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
            excelWriter.fill(records, fillConfig, writeSheet);
            excelWriter.finish();

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("导出白卡清单下发管理错误");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }

}
